package cn.tedu.flowers.controller;

import cn.tedu.flowers.entity.Banner;
import cn.tedu.flowers.mapper.BannerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
public class BannerController {
    @Autowired(required = false)
    BannerMapper mapper;

    @RequestMapping("/banner/select")
    public List<Banner> select() {
        return mapper.select();
    }

@RequestMapping("/banner/delete")
    public void delete(int id){
        mapper.delete(id);
}
@RequestMapping("/banner/insert")
public void insert(MultipartFile pic) throws IOException {
        //得到原始文件名
    String fileName = pic.getOriginalFilename();
    //后缀名
    String suffix=fileName.substring(fileName.lastIndexOf("."));
    //唯一文件名
    fileName= UUID.randomUUID()+suffix;
    String dirPath="d:/upload";
    File dirFile=new File(dirPath);
    //如果文件夹不存在创建文件夹
    if (dirFile.exists()){
        dirFile.mkdirs();
    }
    //完整的文件路径
    String filePath=dirPath+"/"+fileName;
    //保存文件 异常抛出
    pic.transferTo(new File(filePath));

    //保存到数据库
    Banner banner=new Banner();
    banner.setUrl(fileName);
    mapper.insert(banner);
}
}
